<template>
  <div class="tab-container waybill-tab-container tab-fixed" v-if="showdata">
    <el-tabs v-model="activeName">
      <el-tab-pane label="Invoice" name="edit">
        <keep-alive>
          <div class="padding">
            <el-row :gutter="6">
              <!-- <el-col :span="1">&nbsp;</el-col> -->
              <el-form
                ref="waybillMergeInfo"
                :model="waybillMergeInfo"
                :rules="rules"
                size="mini"
                label-width="60px"
              >
                <el-col :span="16">
                  <el-col :span="4"
                    ><h3>M单号：{{ waybillMergeInfo.masterNo }}</h3></el-col
                  >
                  <el-col :span="6"
                    ><h3>
                      合单号：{{ waybillMergeInfo.waybillMergeNo }}
                    </h3></el-col
                  >
                  <el-col :span="4"
                    ><h3>
                      总申报货值：{{ waybillMergeInfo.totalDeclareValue }}
                    </h3></el-col
                  >
                  <el-col :span="4"
                    ><h3>
                      总箱数：{{ waybillMergeInfo.countTotalPackage }}
                    </h3></el-col
                  >
                  <el-col :span="4"
                    ><h3>
                      总申报个数：{{ waybillMergeInfo.totalNum }}
                    </h3></el-col
                  >
                </el-col>
              </el-form>

              <el-col :span="8">
                <el-button-group>
                  <el-button type="primary" size="mini" @click="onMark"
                    >标记代理发票</el-button
                  >
                  <el-button type="primary" size="mini" @click="oneClickMerge"
                    >一键合并发票</el-button
                  >
                  <el-button type="primary" size="mini" @click="onRevoke"
                    >撤销</el-button
                  >
                  <el-button type="primary" size="mini" @click="onMerge"
                    >合并</el-button
                  >
                  <el-button type="primary" size="mini" @click="onDel"
                    >删除</el-button
                  >
                  <el-button type="success" size="mini" @click="onSave"
                    >保存</el-button
                  >
                </el-button-group>
              </el-col>
            </el-row>

            <br />
            <el-card shadow="never">
              <el-table
                ref="invoice"
                :data="tableData"
                stripe
                :row-key="setKey"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                :default-sort="{ prop: 'waybillNo', order: 'ascending' }"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren'
                }"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="30"> </el-table-column>
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                ></el-table-column>
                <ex-table-column
                  v-for="(item, index) in tableColumns"
                  :key="index"
                  :autoFit="true"
                  :prop="item.prop"
                  :label="item.label"
                  :sortable="item.prop === 'waybillNo' ? true : false"
                >
                  <template slot-scope="scope">
                    <template
                      v-if="item.edit && scope.row.edit && !scope.row.isDel"
                    >
                      <el-popover placement="right" width="200" trigger="click">
                        <el-input type="text" v-model="scope.row[item.prop]" />
                        <span slot="reference">{{ scope.row[item.prop] }}</span>
                      </el-popover>
                    </template>
                    <template v-else-if="item.isImg">
                      <el-image
                        style="width: 20px; height: 20px"
                        :src="scope.row[item.prop]"
                        :preview-src-list="[scope.row[item.prop]]"
                      >
                      </el-image>
                    </template>
                    <template v-else>
                      {{ scope.row[item.prop] }}
                    </template>
                  </template>
                </ex-table-column>
              </el-table>
            </el-card>
          </div>
        </keep-alive>
      </el-tab-pane>
      <el-tab-pane label="packingList" name="fileList"> </el-tab-pane>
      <!-- <el-button type="primary" size="mini" @click="allocationTrace"> 确定</el-button> -->
    </el-tabs>
  </div>
</template>
<script>
import ProgressBar from "./components/ProgressBar";
import FileList from "./../alledit/components/FileList";
import BasicInfo from "./components/BasicInfo";
import WaybillInfo from "./components/WaybillInfo";
import MasterOrder from "./components/MasterOrder";
import HouseOrder from "./components/HouseOrder";
import HouseBill from "./components/HouseBill";
import Receivable from "./components/Receivable";
import { ajax } from "@/store/yg/common/utils";
import { clone, randomRange } from "@/utils/clone";
import InvoiceEdit from "../../../main/customer/invoicelist/invoiceEdit.vue";

export default {
  components: {
    ProgressBar,
    FileList,
    BasicInfo,
    WaybillInfo,
    HouseOrder,
    MasterOrder,
    HouseBill,
    Receivable
  },
  InvoiceEditrops: [],

  data() {
    return {
      showdata: false,
      waybillMergeInvoiceData: [{}],
      waybillData: {},
      waybillId: "",
      shippingway: "",
      activeName: "edit",
      countryMap: {},
      serviceItemMap: {},

      waybillMergeInfo: {
        //合单信息
        masterNo: "", //M单号
        waybillMergeNo: "", //合单号
        totalDeclareValue: "", //总申报币值(申报单价之和)
        countTotalPackage: "", //总箱数
        totalNum: "" //总申报个数
      },
      seaAirLiquidationInvoice: [
        {
          //发票对象
          id: "",
          waybillId: 0,
          shipmentId: "",
          referenceId: "",
          sku: 0,
          declareNameCn: "",
          declareNameEn: "",
          brand: "", //品牌
          material: "", //材质
          purpose: "", //用途
          model: "", //型号
          customsCode: "", //海关编码
          mergeInStockTotalPackages: "", //合并运单的总箱数
          purchasingPriceUSD: "", //采购单价转USD
          totalPurchasingPrice: "", //采购总价
          declareValue: "", //申报单价
          declareValue: "", //申报单价
          num: "", //SKU个数
          perSuitNum: "", //每套个数
          measurementUnit: "", //计量单位,个或者套
          imgUrl: "", //产品图片
          num: "", //SKU个数
          perSuitNum: "" //每套个数
        }
      ],
      tableColumns: [
        { prop: "waybillNo", label: "运单号" },
        { prop: "sku", label: "SKU" },
        { prop: "declareNameCn", label: "中文品名" },
        { prop: "declareNameEn", label: "英文品名", edit: true },
        { prop: "material", label: "材质", edit: true },
        { prop: "purpose", label: "用途", edit: true },
        { prop: "brand", label: "品牌", edit: true },
        { prop: "model", label: "型号", edit: true },
        { prop: "customsCode", label: "海关编码", edit: true },
        { prop: "customerTotalPackages", label: "运单箱数" },
        { prop: "purchasingPrice", label: "采购单价", edit: true },
        { prop: "declareValue", label: `申报单价`, edit: true },
        { prop: "declareValueCurrency", label: "申报币种" },
        { prop: "skuNum", label: "数量", edit: true },
        { prop: "measurementUnit", label: "单位" },
        { prop: "perSuitNum", label: "每套个数" },
        { prop: "imgUrl", label: "图片", isImg: true }
      ],
      tableData: [
        {
          waybillNo: "ZX20061216",
          sku: "wer",
          declareNameCn: "wer",
          declareNameEn: "wer",
          material: "wer",
          purpose: "wer",
          brand: "wer",
          model: "wer",
          customsCode: "wer",
          customerTotalPackages: 1,
          purchasingPrice: 12,
          declareValue: 23,
          declareValueCurrency: "USD",
          skuNum: 111,
          measurementUnit: "个",
          perSuitNum: 111,
          rowKey: "m6",
          imgUrl: "http://p1.qhimg.com/t01ab0c3a9103acaead.jpg",
          edit: true,
          children: [
            {
              waybillNo: "ZX20067402",
              sku: "wer3",
              declareNameCn: "wer",
              declareNameEn: "wer",
              material: "wer",
              purpose: "wer",
              brand: "wer",
              model: "wer",
              customsCode: "wer",
              customerTotalPackages: 1,
              purchasingPrice: 12,
              declareValue: 23,
              declareValueCurrency: "USD",
              skuNum: 111,
              measurementUnit: "个",
              perSuitNum: 111,
              rowKey: "m3",
              imgUrl: "http://p1.qhimg.com/t01ab0c3a9103acaead.jpg"
            }
          ]
        },
        {
          waybillNo: "ZX20063172",
          sku: "wer2",
          declareNameCn: "wer",
          declareNameEn: "wer",
          material: "wer",
          purpose: "wer",
          brand: "wer",
          model: "wer",
          customsCode: "wer",
          customerTotalPackages: 1,
          purchasingPrice: 12,
          declareValue: 23,
          declareValueCurrency: "USD",
          skuNum: 111,
          measurementUnit: "个",
          perSuitNum: 111,
          edit: true,
          rowKey: "m1",
          imgUrl: "http://p1.qhimg.com/t01ab0c3a9103acaead.jpg"
        },
        {
          waybillNo: "ZX20067402",
          sku: "wer1",
          declareNameCn: "wer",
          declareNameEn: "wer",
          material: "wer",
          purpose: "wer",
          brand: "wer",
          model: "wer",
          customsCode: "wer",
          customerTotalPackages: 1,
          purchasingPrice: 12,
          declareValue: 23,
          declareValueCurrency: "USD",
          skuNum: 111,
          measurementUnit: "个",
          perSuitNum: 111,
          edit: true,
          rowKey: "m",
          imgUrl: "http://p1.qhimg.com/t01ab0c3a9103acaead.jpg"
        }
      ],
      selection: []
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.waybillId = this.$route.query.waybillId;
    this.shippingway = this.$route.query.shippingway;
    var activeNameTab = this.$route.query.activeName;
    this.showTabByActive(activeNameTab);
    console.info(this.waybillId, this.shippingway);
    this.initWayBillData();
  },
  methods: {
    showTabByActive(activeNameTab) {
      if (null != activeNameTab && activeNameTab != "") {
        this.activeName = activeNameTab;
      }
    },
    async init() {
      const { countryMap } = await initData();
      const { data } = await initAbroadWaybillRender();

      this.countryMap = countryMap;
      this.serviceItemMap = data.serviceItemMap;
    },

    initWayBillData() {
      var param = {};
      param["id"] = this.waybillId;
      param["shippingWayType"] = this.$route.query.shippingway;
      ajax("handleMergeClearanceInvoice", param).then(
        res => {
          if (res.code === 200) {
            this.tableData = Object.values(res.data.idAndLiquidationInvoiceMap);
            this.waybillMergeInfo.waybillMergeNo = res.data.waybillMergeNo;
            debugger;
            console.log(this.waybillMergeInfo.waybillMergeNo);
            console.info("空运数据：", res.data);
          } else {
            this.$message.error(res.message || "请求数据出错");
          }
          this.showdata = true;
        },
        error => {
          console.log(error);
        }
      );
    },
    handleSelectionChange(val) {
      this.selection = val;
      console.log("this.selection :>> ", this.selection);
    },
    async onMark() {
      debugger;
      const data = await ajax("akeyCombinationInvoice", {
        waybillId: waybillId,
        data: JSON.stringify(this.tableData)
      });
      $(this).attr("disabled", "true");
    },
    async oneClickMerge() {
      const data = await ajax("akeyCombinationInvoice", {
        waybillId: waybillId
      });
    },
    // 撤销（合并 || 删除）
    onRevoke() {
      if (this.selection.length === 0) {
        this.$message.error("请选择数据");
        return;
      }
      const tableData = clone(this.tableData);

      for (const i of this.selection) {
        // 撤销删除
        if (i.isDel) {
          this.$set(i, "isDel", 0);
        }
        // 撤销合并
        if (i.children) {
          for (const j of i.children) {
            j.edit = true;
            tableData.push(j);
          }
          // 删除合并数据
          for (const [index, e] of tableData.entries()) {
            if (i.rowKey === e.rowKey) {
              tableData.splice(index, 1);
            }
          }
        }
      }
      this.tableData = tableData;
    },
    // 合并
    onMerge() {
      if (this.selection.length === 0) {
        this.$message.error("请选择要合并的数据");
        return;
      }
      if (this.selection.length === 1) {
        this.$message.error("请至少选择2行数据");
        return;
      }
      const tableData = clone(this.tableData);
      let arr = [];

      for (const i of this.selection) {
        if (i.isDel) {
          this.$message.error(`合并数据包含已删除数据！`);
          return;
        }
        let item = {};

        if (i.children) {
          for (const j of i.children) {
            j.edit = false;
            arr.push(j);
          }
        } else {
          i.edit = false;
          arr.push(i);
        }
        // 删除选中的数据
        for (const [index, e] of tableData.entries()) {
          if (i.sku === e.sku) {
            tableData.splice(index, 1);
          }
        }
      }
      console.log("arr :>> ", arr);
      const skuNum = arr.reduce((p, e) => p + e.skuNum, 0);
      console.log("skuNum :>> ", skuNum);
      // 取数量最大的SKU信息，当一级
      const a = Math.max.apply(
        Math,
        arr.map(function(o) {
          return o.skuNum;
        })
      );
      const p = clone(arr.filter(x => x.skuNum === a)[0]);
      p.skuNum = skuNum;
      // 唯一Key
      p.rowKey = p.waybillNo + randomRange(1, 10);
      p.children = arr;

      console.log("p :>> ", p);
      tableData.push(p);
      this.tableData = tableData;
      console.log("tableData :>> ", tableData);
      // this.$refs.invoice.doLayout();
      console.log("this.tableData :>> ", this.tableData);
    },
    onDel() {
      if (this.selection.length === 0) {
        this.$message.error("请选择要删除的数据");
        return;
      }

      for (const i of this.selection) {
        if (i.children && i.children.length > 0) {
          this.$message.error(`删除数据包含合并数据，请撤销合并数据后再删除`);
          return;
        }
        for (const j of this.tableData) {
          // 根据SKU 标记 删除状态
          if (i.sku === j.sku) {
            this.$set(j, "isDel", 1);
          }
        }
        console.log("this.tableData :>> ", this.tableData);
      }
      // 清空已选
      this.$refs.invoice.clearSelection();
    },
    // 保存（合并 || 删除）
    async onSave() {
      const data = await ajax("saveMergeClearanceInvoice", {
        waybillId: waybillId,
        data: this.tableData
      });
    },
    tableRowClassName({ row, rowIndex }) {
      // console.log("row :>> ", row);
      if (row.isDel) {
        return "warning-row";
      }
      // if()
      return "";
    },
    setKey(row) {
      return row.rowKey;
    }
  }
};
</script>
<style lang="scss" scoped>
.title-icon {
  display: inline-block;
  width: 120px;
}
</style>

<style scoped>
/deep/ .el-tabs__item.is-disabled {
  color: #51abd1;
}

/deep/ .el-form-item__content {
  font-size: 12px;
}

/deep/ .el-autocomplete {
  width: 100%;
}

/deep/ .el-table .warning-row td {
  background-color: gray !important;
}

/deep/ .el-table .success-row td {
  background-color: orange !important;
}
</style>
